<?php


namespace dxw\sdk;

class XorEncrypt
{
    const DEFAULT_KEY_OLD  = "ast!@#";
    const DEFAULT_KEY = "dfgrtgbbygrwxfhrt1235aazcvddfdhnnfwgfhdcpay0706^%&#@!8974642146QEjsdgbvkrJJGGFFsbbjdflsjernxc.lrmgxcvlhktldfg,djkernxsjheridsnfgekdshfierksnfksfkjsh54123sdxcffdyrt545dfhzcbvnfrtw";

    public static function xor_encode($str, $key = '')
    {
        if($key == ''){
            $key = self::DEFAULT_KEY;
        }
        $key = md5($key);
        $randKey = strtoupper(md5(rand(0, 100))); // 相当于动态密钥
        $rand = mt_rand(3,15);
        $k = substr($randKey, 0, $rand);
        $key = $k.$key;
        $tmp = "";
        $keyLen = strlen($key);
        for ($i = 0; $i < strlen($str); $i ++) {
            $tmp .= substr($str, $i, 1) ^ substr($key, ($i%$keyLen), 1);
        }
        return base64_encode($k . substr($randKey, 26, 3).$tmp.substr(md5($tmp.$key), 20, 6). strtoupper( dechex($rand)));
    }

    public static function xor_decode($str, $key = '')
    {
        if($key == ''){
            $key = self::DEFAULT_KEY;
            $_str = self::_xor_decode($str,$key);
            if($_str != ""){
                return $_str;
            }                
            $key = self::DEFAULT_KEY_OLD;
        }
       
        return self::_xor_decode($str,$key);
    }

    private static function _xor_decode($str, $key = '')
    {
        if($key == ''){
            $key = self::DEFAULT_KEY;
        }
        $key = md5($key);
        $str = base64_decode($str);
        $len = strlen($str);
        $rand = hexdec($str[$len-1]);
        $k = substr($str, 0, $rand);
        $key = $k.$key;
        $substr = substr($str, $rand+3, $len - $rand - 10 );
        if(substr($str, $len-7, 6) != substr(md5($substr.$key), 20, 6)){
            return "";
        }
        $tmp = "";
        $keyLen = strlen($key);
        for ($i = 0; $i < strlen($substr); $i ++) {
            $tmp .= substr($substr, $i, 1) ^ substr($key, ($i%$keyLen), 1);
        }
        return $tmp;
    }
}